<template>
  <div class="buy">
    <van-nav-bar class="com-navbar" :border="false">
      <template #left>
        <van-icon name="arrow-left" class="icon-left" @click="onClickLeft" />
      </template>
      <template #title>
        <div class="title">{{ querys.name }}</div>
        <div class="title-des">
         <span>{{realtimeData.close}}</span>
         <span style="margin: 0 10px;">{{ realtimeData.balance }}</span>
         <span>{{realtimeData.rate}}%</span>
        </div>
      </template>
    </van-nav-bar>

    <div  class="container">
      <div  class="head">
        <div  class="top">
          <div  class="name">{{ querys.name }}</div>
          <div  class="symbol">
            <div >{{realtimeData.ticker}}</div>
            .
            <div >{{querys.excode}}</div>
          </div>
        </div>
        <div  class="bottom">
          <div  class="left">
            <div  class="price">{{ realtimeData.close }}</div>
            <div  class="index">
              <div >{{ realtimeData.balance }}</div>
              <div >{{realtimeData.rate < 0 ? '' : '+'}} {{ realtimeData.rate }}%</div>
            </div>
          </div>
          <div >
            <p >{{t('High')}}</p>
            <p  class="color_g">{{ realtimeData.high }}</p>
          </div>
          <div >
            <p >{{t('Low')}}</p>
            <p  class="color_g">{{ realtimeData.low }}</p>
          </div>
        </div>
      </div>
      <div  class="cell">
        <div  class="cell-item">
          <div  class="cell-item-name">{{t('Current Price')}}</div>
          <div  class="cell-item-value">{{ realtimeData.close }}</div>
        </div>
        <div  class="cell-item">
          <div  class="cell-item-name">{{t('Quantity')}}</div>
          <div  class="cell-item-value">
            <van-field :placeholder="t('Please Enter Quantity')" v-model="quantity" :readonly="true"  clickable @touchstart.stop="show = true"></van-field>
            <van-number-keyboard
              v-model="quantity"
              placeholder="请输入"
              :show="show"
              :maxlength="10"
              @blur="show = false"
            />
          </div>
        </div>
        <div  class="cell-item">
          <div  class="cell-item-name">{{t('Commission Ratio')}}</div>
          <div  class="cell-item-value">0.2%</div>
        </div>
        <div  class="cell-item">
          <div  class="cell-item-name">{{t('Purchase Amount')}}</div>
          <div  class="cell-item-value">₹{{ purchase_amount }}</div>
        </div>
        <div  class="cell-item">
          <div  class="cell-item-name">{{t('Service Fee')}}</div>
          <div  class="cell-item-value">₹{{ fee }}</div>
        </div>
        <div  class="cell-item">
          <div  class="cell-item-name">{{t('Trading Balance')}}</div>
          <div  class="cell-item-value">
            ₹{{ balance}}
          </div>
        </div>
      </div>
      <div  class="btns">
        <div  class="btn-item1" @click="buyHandler">{{t('Buy')}}</div>
        <div  class="btn-item2" @click="goHolding">{{t('Sell')}}</div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { useRouter, useRoute } from "vue-router"
import { get, post } from '@/utils/request'
import { ref, computed } from 'vue'
import { closeToast, showLoadingToast, showSuccessToast, showToast } from 'vant'
import { checkExchangeTimeRage } from '@/store/index'
import 'vant/es/number-keyboard/style'
import { t } from '@/languages'
const router = useRouter();
const querys = useRoute().query
const realtimeData = ref({})
const show = ref(false)
const thToken = import.meta.env.VITE_APP_THTOKEN
const quantity = ref('')
const detail = ref({})


const purchase_amount = computed(() => {
  return (quantity.value * realtimeData.value.close).toFixed(2)
})
const fee = computed(() => {
  return (purchase_amount.value * 0.002).toFixed(2)
})
const balance = computed(() => {
  return (detail.value.balance - purchase_amount.value).toFixed(2)
})


function onClickLeft() {
  router.back();
}

function goHolding() {
  router.push('/holdings/index')
}

async function buyHandler() {
  const isInTime = checkExchangeTimeRage()
  if(!isInTime) {
    showToast(t('Non trading hours'))
    return
  }
  if(!quantity.value) {
    showToast(t('Please Enter Quantity'))
    return
  }
  if(balance.value < 0) {
    showToast(t('Sory, your balance is running low'))
    return
  }
  try {
    showLoadingToast()
    const res = await post('/api/app/stock/in/', {
      current_price: realtimeData.value.close,
      quantity: +quantity.value,
      commission_ratio: 0.002,
      ticker: realtimeData.value.ticker
    })
    showSuccessToast(t('Purchase successful'))
    goHolding()
  } catch (error) {
    console.log(error)
    closeToast()
  }
}

async function getRealtimeData() {
  return await get(`/th/fin/stock/${querys.excode}/realtime`, {
    token: thToken,
    ticker: querys.ticker,
    columns:`close,pre_close,high,low,ticker`
  })
}

async function getUserInfo() {
  return await get(`/api/app/getmyinfo/`, {})
}

function realDataInit(res) {
  const data = res[0] || {}
  const balance = Math.ceil((data.close - data.pre_close)).toFixed(2)
  const rate = ((data.close - data.pre_close) / data.pre_close).toFixed(2)
  realtimeData.value = {
    ...data,
    balance: balance > 0 ? `+ ${balance}` : balance,
    rate: rate === 0 ? 0.00 : rate
  }
}

async function initData() {
  try {
    showLoadingToast()
    const res = await Promise.all([getRealtimeData(), getUserInfo()])
    realDataInit(res[0] ? res[0] : [{}])
    detail.value = res[1] ? res[1] : {}
  } catch (error) {
    console.log(error)
  } finally {
    closeToast()
  }
}
initData()
</script>

<style lang="scss">
.van-key {
  color: #333;
}
.van-nav-bar .van-nav-bar__title {
  font-weight: 600;
  background: linear-gradient(0deg, #62f792, #63fddb);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  text-fill-color: transparent;
}
.com-navbar {
  background: #0f3a40;
}
.buy .title {
  color: #fff;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 0.37333rem;
}

.buy .title-des {
  font-size: 0.32rem;
  color: #fff;
}

.buy .container {
  padding: 0.4rem;
}

.buy .container .head .top {
  margin-top: 0.53333rem;
  margin-bottom: 0.53333rem;
}

.buy .container .head .top .name {
  color: #fff;
  font-size: 0.4rem;
  font-weight: 600;
}

.buy .container .head .top .symbol {
  display: flex;
  color: #ccc;
  font-size: 0.32rem;
  margin-top: 0.13333rem;
}

.buy .container .head .bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-right: 0.26667rem;
  margin-bottom: 0.4rem;
}

.buy .container .head .bottom .left {
  display: flex;
  align-items: center;
}

.buy .container .head .bottom .color_g {
  margin-top: 0.13333rem;
  color: #62f792;
}

.buy .container .head .bottom .price {
  color: #62f792;
  font-size: 0.8rem;
  font-weight: 600;
}

.buy .container .head .bottom .index {
  color: #4baf68;
  font-size: 0.32rem;
  margin-left: 0.13333rem;
}

.buy .container .cell {
  border: 0.02667rem solid #2b4e5a;
  border-radius: 0.16rem;
}

.buy .container .cell .cell-item {
  display: flex;
  height: 1.06667rem;
  line-height: 1.06667rem;
  border-radius: 0.13333rem;
  border-bottom: 0.02667rem dotted #0f3a40;
  padding: 0 0.26667rem;
  margin-bottom: 0.26667rem;
}

.buy .container .cell .cell-item .cell-item-name {
  color: #ccc;
}

.buy .container .cell .cell-item .cell-item-value {
  flex: 1;
  text-align: right;
  font-weight: 600;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.buy .container .cell .cell-item .cell-item-value .van-cell {
  padding: 0;
  padding-left: 0.26667rem;
  border-radius: 0.13333rem;
  height: 1.06667rem;
  background-color: unset;
}

.buy .container .cell .cell-item .cell-item-value .van-field__body {
  height: 100%;
  font-size: 0.42667rem;
  font-weight: 600;
  color: #fff;
}

.buy
  .container
  .cell
  .cell-item
  .cell-item-value
  .van-field__body
  .van-field__control {
  text-align: right;
  color: #fff;
}

.buy .container .cell .cell-item-time {
  flex-direction: column;
  height: 3.46667rem;
}

.buy .container .cell .cell-item-time-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
}

.buy .container .cell .cell-item-time-container .cell-item-time-item {
  width: 1.6rem;
  border-radius: 0.13333rem;
  border: 0.02667rem solid #28ba98;
  color: #28ba98;
}

.buy
  .container
  .cell
  .cell-item-time-container
  .cell-item-time-item
  .cell-item-time-item-item {
  text-align: center;
  border-bottom: 0.02667rem solid #28ba98;
}

.buy
  .container
  .cell
  .cell-item-time-container
  .cell-item-time-item
  .cell-item-time-item-rate {
  text-align: center;
}

.buy .container .cell .cell-item-time-container .cell-item-time-item-active {
  background-image: linear-gradient(120deg, #84fab0, #8fd3f4);
  color: #fff;
}

.buy .container .cell .cell-item-balance {
  color: #000;
  font-size: 0.37333rem;
}

.buy .container .btns {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-around;
  padding: 0.53333rem 0.13333rem;
  border-top: 0.02667rem solid #ececec;
}

.buy .container .btns .btn-item1,
.buy .container .btns .btn-item2 {
  padding: 0.26667rem 1.06667rem;
  color: #fff;
  border-radius: 0.4rem;
  color: #0d111a;
  font-size: 0.37333rem;
  font-weight: 600;
}

.buy .container .btns .btn-item1 {
  background: linear-gradient(270deg, #62f792, #63fddb);
}

.buy .container .btns .btn-item2 {
  background: linear-gradient(270deg, #d02f5e, #fed053);
}
</style>
